package com.hk.service.demo.impl;

import com.alibaba.fastjson.JSON;
import com.hk.component.RedisCache;
import com.hk.domain.entity.SysUser;
import com.hk.exception.BizException;
import com.hk.service.demo.LoginServcie;
import com.hk.utils.JwtUtil;
import com.hk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class LoginServcieImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public R login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(), sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        log.info("authenticate: {}", JSON.toJSON(authenticate));
        if (Objects.isNull(authenticate)) {
            throw new BizException("用户名或密码错误~~");
        }
        //获取登录信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        log.info("login ：{}", JSON.toJSON(loginUser));

        //获取userId
        String userId = loginUser.getUser().getId().toString();
        //根据userId创建令牌
       String jwt = JwtUtil.createJWT(userId);
        redisCache.setCacheObject("login:" + userId, loginUser);

        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return R.ok().put("data",map);
    }

    @Override
    public R logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userId);
        return R.ok("退出成功~");
    }
}
